package top.suven.base.core.db;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TransactionalConfig
 * @Author suven.wang
 * @Description //TODO ${END}$
 * @CreateDate 2018-09-14  10:03
 * @WeeK 星期五
 * @Version v2.0
 **/
@Configuration
@Aspect
@EnableConfigurationProperties({DataSourceAutoConfig.class})
public class DatasourceTransactionalConfig {

    private static final int TX_METHOD_TIMEOUT = 5;
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* cn.com.gc.hsz..service.*.*(..))";

    private DataSource dataSource;

    @Resource(name="dataSource")
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    @Bean
    public PlatformTransactionManager txManager() {
        DSAnnoExplain.initDatasource();
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("txAdvice")
    public TransactionInterceptor txAdvice() {
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        /*只读事务，不做更新操作*/
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED );
        /*当前存在事务就使用当前事务，当前不存在事务就创建一个新的事务*/
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();

        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredTx.setTimeout(TX_METHOD_TIMEOUT);
        Map<String, TransactionAttribute> txMap = new HashMap<>();
        //查询的方法
        txMap.put("get*", readOnlyTx);
        txMap.put("query*", readOnlyTx);

        //写的方法
        txMap.put("add*", requiredTx);
        txMap.put("save*", requiredTx);
        txMap.put("insert*", requiredTx);
        txMap.put("update*", requiredTx);
        txMap.put("delete*", requiredTx);

        source.setNameMap( txMap );
        TransactionInterceptor txAdvice = new TransactionInterceptor(txManager(), source);
        return txAdvice;
    }


    /**切面拦截规则 参数会自动从容器中注入*/
    @Bean
    public AspectJExpressionPointcutAdvisor pointcutAdvisor(TransactionInterceptor txAdvice){
        AspectJExpressionPointcutAdvisor pointcutAdvisor = new AspectJExpressionPointcutAdvisor();
        pointcutAdvisor.setAdvice(txAdvice);
        pointcutAdvisor.setExpression(AOP_POINTCUT_EXPRESSION);
       String name = pointcutAdvisor.getPointcut().getClass().getName();

        return pointcutAdvisor;
    }



//    @Before("txManager()")
//    public void before(JoinPoint point){
//        /**
//         * Signature 包含了方法名、申明类型以及地址等信息
//         */
//        String[] packages = point.getClass().getPackage().getName().split(".");
//        if(packages.length > 4){
//           String model =  packages[4];
//            DataSourceGroupNameEnum groupName = DataSourceGroupNameEnum.getDataSourceGroupNameEnumByValue(model);
//
//            DataChooseParam dcp = new DataChooseParam(groupName.name(),DataSourceEnum.MASTER);
//            DataSourceHolder.putDataSource(dcp);
//        }
//
//    }


}
